package concurrency.chapter10;

import java.util.concurrent.TimeUnit;

/**
 * @author honway.liu
 * @date 2019-06-26 12:06
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
public class VolatileDemo {

    private static volatile int INIT_VAL = 0;

    private static final int MAX_VAL = 5;


    public static void main(String[] args) {
        new Thread(() -> {
            int localVal = INIT_VAL;
            while (localVal < MAX_VAL) {
                if (localVal != INIT_VAL) {
                    System.out.println("local val now is: " + INIT_VAL);
                    localVal = INIT_VAL;
                }
            }
        }, "READ").start();

        new Thread(() -> {
            while (INIT_VAL < MAX_VAL) {
                System.out.println("local val is update to: " + (INIT_VAL++));
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "WRITER").start();

    }

}
